package com.wsm.util.httpclient.util;

import com.wsm.util.httpclient.config.HttpUtilConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;


/**
 * @author ：wangshimin
 * @date ：Created in 2021-02-27 下午 12:06
 * @description：http请求工具类
 * @version:
 */
public class HttpClientUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    private static PoolingHttpClientConnectionManager CONN_MGR;

    private static RequestConfig REQUEST_CONFIG;


    public void init(HttpUtilConfig httpUtilConfig) {
        // 设置连接池
        CONN_MGR = new PoolingHttpClientConnectionManager();
        // 设置连接池大小
        CONN_MGR.setMaxTotal(httpUtilConfig.getMaxTotal());
        CONN_MGR.setDefaultMaxPerRoute(httpUtilConfig.getMaxTotal());
        CONN_MGR.setValidateAfterInactivity(httpUtilConfig.getValidateAfterInactivity());

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(httpUtilConfig.getMaxTimeOut());
        // 设置读取超时
        configBuilder.setSocketTimeout(httpUtilConfig.getMaxTimeOut());
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(httpUtilConfig.getMaxTimeOut());
        REQUEST_CONFIG = configBuilder.build();
    }

    /**
     * 发送 GET 请求（HTTP）
     *
     * @param url
     * @param headers 需要添加的httpheader参数
     * @return
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, Object> params) {
        boolean isSsl = url.startsWith("https://");
        return result(getCloseableHttpClient(isSsl), getHttpGet(url, headers, params, isSsl));
    }

    /**
     * 发送 POST 请求（HTTP），K-V形式
     *
     * @param url
     * @param headers 需要添加的httpheader参数
     * @return
     */
    public static String doPostByForm(String url, Map<String, String> headers, Map<String, Object> params) {
        boolean isSsl = url.startsWith("https://");
        return result(getCloseableHttpClient(isSsl), getHttpPost(url, headers, params, isSsl));
    }

    /**
     * 发送 POST 请求（HTTP），JSON形式
     *
     * @param url
     * @param headers 需要添加的httpheader参数
     * @return
     */
    public static String doPostByJson(String url, Map<String, String> headers, Object json) {
        boolean isSsl = url.startsWith("https://");
        return result(getCloseableHttpClient(isSsl), getHttpPost(url, headers, json, isSsl));

    }

    private static String result(CloseableHttpClient httpClient, HttpUriRequest request) {
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (entity != null) {
                    return EntityUtils.toString(entity, "utf-8");
                }
            }
            if (entity != null) {
                log.error("HttpClient-util: response error===>{}", EntityUtils.toString(entity, "utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 创建SSL安全连接
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private static SSLConnectionSocketFactory createSslConnSocketFactory() {
        // 创建TrustManager
        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        // TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLS");
            // 使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx);
            return sslsf;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加header信息
     */
    private static void addHttpHeaders(Map<String, String> headers, HttpUriRequest httpUriRequest) {
        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {
                httpUriRequest.addHeader(key, headers.get(key));
            }
        }
    }

    private static HttpGet getHttpGet(String url, Map<String, String> headers, Map<String, Object> params, Boolean isSsl) {
        if (null == url || url.length() == 0) {
            return null;
        }
        url = getUrlString(params, url);
        HttpGet httpGet = new HttpGet(url);
        addHttpHeaders(headers, httpGet);
        if (isSsl) {
            httpGet.setConfig(REQUEST_CONFIG);
        }
        return httpGet;
    }


    /**
     * map
     */
    private static HttpPost getHttpPost(String url, Map<String, String> headers, Map<String, Object> params, Boolean isSsl) {
        if (null == url || url.length() == 0) {
            return null;
        }
        HttpPost httpPost = getHttpPost(url, headers, isSsl);
        setHttpPostEntity(params, httpPost);
        return httpPost;
    }

    /**
     * json
     */
    private static HttpPost getHttpPost(String url, Map<String, String> headers, Object params, Boolean isSsl) {
        if (null == url || url.length() == 0) {
            return null;
        }
        HttpPost httpPost = getHttpPost(url, headers, isSsl);
        setHttpPostEntity(params, httpPost);
        return httpPost;
    }

    private static HttpPost getHttpPost(String url, Map<String, String> headers, Boolean isSsl) {
        HttpPost httpPost = new HttpPost(url);
        addHttpHeaders(headers, httpPost);
        if (isSsl) {
            httpPost.setConfig(REQUEST_CONFIG);
        }
        return httpPost;
    }


    private static CloseableHttpClient getCloseableHttpClient(boolean isSsl) {
        return
                isSsl ?
                        HttpClients.custom().setSSLSocketFactory(createSslConnSocketFactory())
                                .setConnectionManager(CONN_MGR).setDefaultRequestConfig(REQUEST_CONFIG).build()
                        :
                        HttpClients.createDefault();
    }


    /**
     * 封装url地址
     */
    private static String getUrlString(Map<String, Object> params, String apiUrl) {
        if (params.isEmpty()) {
            return apiUrl;
        }
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        apiUrl += param;
        return apiUrl;
    }

    private static void setHttpPostEntity(Map<String, Object> params, HttpPost httpPost) {
        List<NameValuePair> pairList = new ArrayList<>(params.size());
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            pairList.add(pair);
        }
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, java.nio.charset.StandardCharsets.UTF_8));
    }

    private static void setHttpPostEntity(Object json, HttpPost httpPost) {
        // 解决中文乱码问题
        StringEntity stringEntity = new StringEntity(JsonUtil.obj2String(json), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
    }
}